# coding:utf-8
from typing import Union, Callable

from PyQt6.QtCore import Qt
from PyQt6.QtGui import QIcon
from PyQt6.QtWidgets import QWidget, QVBoxLayout
from qfluentwidgets import ScrollArea, FlowLayout, BodyLabel, setFont, FluentIconBase

from common import signalBus
from .base import BaseScrollArea
from ..cards import SampleCard
from ..widgets import SlidingStackedWidget


class TitleInterface(SlidingStackedWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.fistPage = ScrollArea(self)
        self.view = QWidget()
        self.verticalLayout = QVBoxLayout(self.view)
        self.titleLabel = BodyLabel('欢迎使用 FluentWidgets', self.view)
        self.flowLayout = FlowLayout(needAni=True, isTight=True)
        self.__initWidgets()

    def __initWidgets(self):
        self.setObjectName('TitleInterface')

        self.fistPage.setWidget(self.view)
        self.fistPage.setWidgetResizable(True)
        self.view.setAutoFillBackground(False)
        self.fistPage.enableTransparentBackground()
        setFont(self.titleLabel, 24)
        self.fistPage.setViewportMargins(36, 24, 36, 10)

        self.verticalLayout.setAlignment(Qt.AlignmentFlag.AlignTop)
        self.verticalLayout.addWidget(self.titleLabel)
        self.verticalLayout.addLayout(self.flowLayout)

        self.addWidget(self.fistPage)

    def addDefaultSampleCard(
            self, icon: Union[str, QIcon, FluentIconBase],
            title: str, content: str, routeKey: str,
            clicked: Callable = None
    ):
        """ 添加默认样品卡 """
        card = SampleCard(icon, title, content, self)
        card.setObjectName(routeKey)
        if clicked:
            card.clicked.connect(clicked)
        self.flowLayout.addWidget(card)
        return card

    def addShortcut(self, widget: BaseScrollArea):
        """ 添加快捷键 """
        card = self.addDefaultSampleCard(
            widget.icon, widget.title, widget.description, widget.object_name,
            lambda: signalBus.switchToSampleCard.emit(widget.parent().objectName(), widget.object_name)
        )
        return card

    def addSampleCard(self, widget: BaseScrollArea):
        """ 添加样品卡 """
        card = self.addDefaultSampleCard(
            widget.icon, widget.title, widget.description, widget.object_name,
            lambda: self.setCurrentWidget(widget)
        )
        self.addWidget(widget)
        widget.returned.connect(lambda: self.setCurrentWidget(self.fistPage))
        if widget.is_shortcut:
            signalBus.addShortcut.emit(widget)
        return card

    def setTitle(self, title: str):
        """ 设置标题 """
        self.titleLabel.setText(title)
